package com.hjj.web.controller;


import com.hjj.web.entity.User;
import com.hjj.web.entity.vo.WebSocketDemoQueryDTO;
import com.hjj.web.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.messaging.simp.user.SimpUser;
import org.springframework.messaging.simp.user.SimpUserRegistry;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author hejiajun
 * @since 2020-12-04
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    IUserService userService;

    @Autowired
    private SimpMessagingTemplate messagingTemplate;

    @Autowired
    private SimpUserRegistry userRegistry;

    /**
     * 根据 登录人报存的sessionId 查询 对应的基本信息
     *
     * @param httpSession
     * @return
     */
    @GetMapping("/currentUser")
    public User currentUser(HttpSession httpSession) {
        Long userId = (Long) httpSession.getAttribute("userId");
        String name = userService.getNameById(userId);
        return new User(userId, name);
    }

    /**
     * 查询当前在线人数
     *
     * @param currentUser
     * @return
     */
    @PostMapping(value = "/onlineUsers")
    public Set<String> onlineUsers(@RequestParam("currentUser") String currentUser) {
        log.info("当前在线人数:" + userRegistry.getUserCount());
        int i = 1;
        for (SimpUser user : userRegistry.getUsers()) {
            log.info("用户" + i++ + "---" + user);
        }
        Set<String> set = userRegistry.getUsers().stream().filter(m -> !m.getName().equals(currentUser)).map(m -> m.getName()).collect(Collectors.toSet());
        return set;
        //发送消息给指定用户
        //messagingTemplate.convertAndSendToUser("test", "/queue/message", new ServerMessage("服务器主动推的数据"));
    }

    /**
     * 根据 用户名查询对应的 用户信息
     *
     * @param userName
     * @return
     */
    @GetMapping("getUserId")
    public User getUserId(@RequestParam("userName") String userName) {
        User a = userService.getUserByName(userName);
        return a;
    }

    /**
     * 私聊。
     *
     * @param dto
     */
    @MessageMapping(value = "/toUser")
    public void templateTest1(WebSocketDemoQueryDTO dto) {
        log.info("私聊消息sendName" + dto.getSendName());
        //发送消息给指定用户
        messagingTemplate.convertAndSendToUser(dto.getSendName(), "/queue/getResponse", dto);
    }

    /**
     * 广播系统消息。
     *
     * @param dto
     */
    @MessageMapping(value = "/sendToAll")
    public void sendToAll(WebSocketDemoQueryDTO dto) {
        //发送系统广播消息
        messagingTemplate.convertAndSend("/topic/getSendMessage", dto.getMessage());
    }

}
